package org.devocean.groupbuying.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.devocean.groupbuying.dao.DiscountDAO;
import org.devocean.groupbuying.domain.Discount;
import org.springframework.stereotype.Repository;

@Repository
public class DiscountDAOImpl implements DiscountDAO {

	@PersistenceContext
	private EntityManager em;

	public List<Discount> findAllDiscounts() {

		return em.createQuery("select d from Discount d", Discount.class)
				.getResultList();
	}

	public long countDiscount() {
		return em.createQuery("select count(d) from Discount d", long.class)
				.getSingleResult();
	}

	public Discount findDiscountById(Integer discountID) {
		return em.find(Discount.class, discountID);
	}

	public void deleteDiscount(Integer discountID) {
		final Discount discount = em.find(Discount.class, discountID);
		if (discount != null) {
			em.remove(discount);
		}

	}

	public Discount saveDiscount(Discount discount) {
		em.persist(discount);
		return discount;
	}

	public Discount updateDiscount(Discount discount) {
		em.merge(discount);
		return discount;
	}

	public long countDiscountValidKeys(Integer discountID) {
		final Query query = em.createQuery("SELECT COUNT(s)FROM SerialKey s "
				+ "INNER JOIN s.voucher v " + "INNER JOIN v.discount d "
				+ "WHERE d.discountID =:di AND s.valid=1", Long.class);
		query.setParameter("di", discountID);
		return (Long) query.getSingleResult();
	}

}
